package cn.xeblog.server.action.specialAc;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.lang.ConsoleTable;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 今日油价查询
 *
 * @author ZhangLei
 * @date 2024/8/9 11:16
 */
@Slf4j
public class OilSearchUtil {

    private static final TimedCache<String, OilData> TIMEDCACHE = CacheUtil.newTimedCache(1000 * 60 * 30);

    public static void main(String[] args) {
        doSearch("安徽");

    }

    public static String oilSearch(String province) {
        OilData oilData = TIMEDCACHE.get(province);
        if (oilData != null) {
            return getConsoleTableStr(oilData);
        }

        Result result = doSearch(province);
        OilData data = result.getData();
        if (data == null || StrUtil.isEmpty(data.getProvince())) {
            return result.getMsg();
        } else {
            TIMEDCACHE.put(province, data);
            return getConsoleTableStr(data);
        }
    }

    private static Result doSearch(String province) {
        try {
            HttpRequest request = HttpUtil.createGet("https://www.mxnzp.com/api/oil/search");
            request.form("province", province);
            request.form("app_id", "oamepjimqmevnqxj");
            request.form("app_secret", "6lhsxr5VCIZ10E7yyqpziKuMBfJSwum1");
            String response = request.execute().body();
            return JSONObject.parseObject(response, new TypeReference<Result>() {
            });
        } catch (Exception e) {
            log.error("查询失败！", e);
            return new Result("500", "查询失败，请联系管理员。", null);
        }
    }

    private static String getConsoleTableStr(OilData oilData) {
        ConsoleTable consoleTable = ConsoleTable.create();
        consoleTable.addHeader("省份", "0号柴油", "90号汽油", "92号汽油", "95号汽油", "98号汽油");
        consoleTable.addBody(oilData.getProvince(), oilData.getT0(), oilData.getT89(), oilData.getT92(), oilData.getT95(), oilData.getT98());
        return consoleTable.toString();
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Result {
        private String code;
        private String msg;
        private OilData data;
    }

    @Data
    public static class OilData {
        private String province;
        private String t0;
        private String t89;
        private String t92;
        private String t95;
        private String t98;
    }
}
